<template>
  <a-modal v-model:visible="modalVisible" @ok="handleOk" @cancel="handleCancel">
    <template #title> 选择人员 </template>
    <a-checkbox-group
      direction="vertical"
      v-model="selectedIds"
      @change="change"
    >
      <a-checkbox v-for="item in humanList" :key="item.id" :value="item.id">
        {{ item.name }}
      </a-checkbox>
    </a-checkbox-group>
  </a-modal>
</template>
<script setup lang="ts">
import { GetHumanRosterList } from '@/apis/management/human/humanRoster';
import { useVModel } from '@vueuse/core';

const props = withDefaults(
  //参数说明
  defineProps<{
    visible: boolean;
    data: any[];
  }>(),
  {
    visible: false
  }
);
const emits = defineEmits(['update:visible', 'update:data', 'submit']);
const modalVisible = useVModel(props, 'visible', emits);
const selectedData = useVModel(props, 'data', emits);
const handleOk = () => {
  selectedData.value.length = 0;

  selectedIds.value.forEach((item) => {
    if (item === 0) {
      const index = selectedData.value.findIndex((ele) => ele.id === 0);
      if (index >= 0) return;
      (selectedData.value as any).push({ id: 0, name: '所有人', type: 5 });
      return;
    }
    const humanInfo = humanList.value.find((human) => human.id === item);
    if (!humanInfo) return;
    const { id, name } = humanInfo;
    const index = selectedData.value.findIndex((ele) => ele.id === id);
    if (index >= 0) return;
    (selectedData.value as any).push({ id, name, type: 1 });
  });

  modalVisible.value = false;
  emits('submit');
};
const handleCancel = () => {
  modalVisible.value = false;
};
const change = async (e, v) => {
  let arr = Array.from({ length: 16 }, (_, i) => i + 109);
  console.log(e, v);

  // await delFlowParticipantByIds({ ids: arr });
};
const humanList = ref<any[]>([]);
const getHumanList = async () => {
  const res = await GetHumanRosterList({
    pageNumber: 0,
    pageSize: 20,
    typeName: 5
  });
  humanList.value = res?.content || [];
  // humanList.value.unshift({ id: 0, name: '所有人', type: 5 });
};
const selectedIds = ref<any[]>([]);
watch(
  () => modalVisible.value,
  () => {
    if (!modalVisible.value) return;
    selectedIds.value = [];
    if (selectedData.value?.length) {
      selectedData.value.forEach((item: any) => {
        const index = selectedIds.value.findIndex(
          (objId) => objId === item.objId
        );
        if (index >= 0) return;
        if (item.objType === 5) selectedIds.value.push('0');
        else {
          console.log('selectedIds.value', item);
          selectedIds.value.push(item?.objId);
        }
      });
    }

    getHumanList();
  }
);
</script>
